﻿using System;
using System.Drawing;
using System.Windows.Forms;
using CoCoonCoreWM6;
using System.Drawing.Imaging;

namespace CoCoonWM6
{
    class Display
    {
        private Bitmap frame;
        private Int32 hSize;
        private Int32 vSize;
        private CoCo coco;
        
        public Display(CoCo c)
        {
            hSize = 256;
            vSize = 192;
            frame = new Bitmap(hSize, vSize, PixelFormat.Format24bppRgb);
            coco = c; 
        }

        public int Paint(Graphics g)
        {
            Pixel[] pixels = coco.VideoOut();
            
            int c = 0;
            Rectangle r = new Rectangle(0, 0, frame.Width, frame.Height);
            BitmapData bmd = frame.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            for (int y = 0; y < bmd.Height; y++)
            {
                unsafe
                {
                    byte* row = (byte*)bmd.Scan0 + (y * bmd.Stride);
                    for (int x = 0; x < bmd.Width*3; x = x + 3)
                    {
                        row[x] = pixels[c].Blue;
                        row[x + 1] = pixels[c].Green;
                        row[x + 2] = pixels[c].Red;
                        c++;
                    }
                }
            }
            frame.UnlockBits(bmd);
            g.DrawImage(frame, 0, 0);

            return 0;
        }

        public void Draw(PictureBox p)
        {
            Pixel[] pixels = coco.VideoOut();
            //of: 49152 - 40960 = null? 
            int c = 0;
            Rectangle r = new Rectangle(0, 0, frame.Width, frame.Height);
            BitmapData bmd = frame.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            for (int y = 0; y < bmd.Height; y++)
            {
                if (pixels[c] != null)
                {
                    unsafe
                    {
                        byte* row = (byte*) bmd.Scan0 + (y*bmd.Stride);
                        for (int x = 0; x < bmd.Width*3; x = x + 3)
                        {
                            row[x] = pixels[c].Blue;
                            row[x + 1] = pixels[c].Green;
                            row[x + 2] = pixels[c].Red;
                            c++;
                        }
                    }
                }
            }
            frame.UnlockBits(bmd);

            p.Image = frame;
        }
    }
}
